<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
	<meta charset="UTF-8">
    <title>入库申请登记</title>
    <link rel="stylesheet"  href="/bootstrap/bootstrap-5.3.3-dist/css/bootstrap.min.css" />
   	<link rel="stylesheet" href="/css/stock/c/Warehousing_Application_Registration.css" />
   <style type="text/css">
	   #proRegistraModal select{
		   width: 100px;
		   margin-right: 20px;
	   }
    </style>
</head>
<body style="padding: 15px 50px;background-color: #eeeeee;">
	<div class="panel-heading hhead">
		<nav aria-label="breadcrumb">
		  <ol class="breadcrumb">
		  	<span style="color: blue;">您正在做的业务是：</span>
		    <li class="breadcrumb-item"><a href="#">库存管理</a></li>
		    <li class="breadcrumb-item"><a href="#">入库申请管理</a></li>
		    <li class="breadcrumb-item active" aria-current="page">入库申请登记</li>
		  </ol>
		</nav>
	</div>

    <div style="margin-bottom: 2px">
        <div style="display: inline;margin-left: 72%;">
            <button class="btn btn-primary" id="btnAdd" data-bs-toggle="modal" data-bs-target="#proRegistraModal">添加产品</button>
            <button class="btn btn-primary" id="delete">删除产品</button>
            <button class="btn btn-primary" id="submit">预览</button>
            <button class="btn btn-primary">返回</button>
        </div>
    </div> <!-- 此div改用栅格来做 -->
    <div id="designListBox">
        <div style="text-align: center">
            <h3>入库申请单</h3>
        </div>
		<form id="searchForm">
			<input type="hidden" id="page" name="pageNum" value="1">
			<input type="hidden" id="pageSize" name="pageSize" value="5">
			<input type="hidden" name="checkTag" value="1">
			<input type="hidden" name="firstId" value="">
			<input type="hidden" name="secondId" value="">
			<input type="hidden" name="thirdId" value="">
<%--			<input type="hidden" name="useId" value="01">--%>
			<input type="hidden" name="startDate" value="">
			<input type="hidden" name="endDate" value="">
			<%--		<input type="hidden" name="designModuleTag" value="0">--%>
		</form>
        <div style="padding: 30px">
           <table class="tbl1">
               <tr>
                   <td class="col1" name="">入库人：</td>
                   <td class="col2" id="storer">${user.loginId}</td>
                   <td class="col1">入库理由：</td>
                   <td class="col2">
                   	<select name="" id="reason">
                   		<option value="1">库存初始</option>
                   		<option value="2">赠送</option>
                   		<option value="3">内部借领</option>
                   		<option value="4">其他借领</option>
                   	</select>
                   </td>
               </tr>
           </table>

            <table class="table table-bordered" style="margin: 15px auto;">
                <thead>
                    <tr>
                        <th>点选</th>
						<th>产品名称</th>
						<th>产品编号</th>
                        <th>描述</th>
						<th>数量</th>
						<th>单位</th>
                        <th>成本单价（元）</th>
						<th>小计（元）</th>
                    </tr>
                </thead>
                <tbody id="template1">

                </tbody>

            </table>

            <table class="tbl3">
            	<tr>
                    <td class="col1">总件数：</td>
                    <td class="col2" id="amountSum"></td>
                    <td class="col1">总金额：</td> <td class="col2" id="costPriceSum"></td>
                </tr>
                <tr>
                    <td class="col1">登记人：</td>
                    <td class="col2"><input type="text" class="txt_under_line" id="register"></td>
                    <td class="col1">登记时间：</td> <td class="col2" id="registerTime"></td>
                </tr>
                <tr>
                    <td class="col1">备注：</td>
                    <td colspan="3" style="padding-top: 5px">
                        <textarea rows="4" cols="100" id="remark"></textarea>
                   </td>
                </tr>
             </table>
        </div>
    </div>
    
    <div class="modal fade" id="proRegistraModal" data-bs-backdrop="static" data-bs-keyboard="false" tabindex="-1" aria-labelledby="staticBackdropLabel" aria-hidden="true">
			<div class="modal-dialog modal-xl">
					<div class="modal-content">
						<div class="modal-header">
							<h2>添加产品</h2>
							<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
						</div>
						<div class="modal-body">
							<div class="container-fluid">
								<div id="bodyBox">
									<form>
										<div class="panel product">
											<div class="panel-heading hhead">
												<div>
													请选择产品I级分类：<select id="firstLevel"><option>请选择</option></select>
													请选择产品II级分类：<select id="secondLevel"><option>请选择</option></select>
													请选择产品III级分类：<select id="thirdLevel"><option>请选择</option></select>
													<button class="btn btn-primary">查询</button>
												</div>
												<div>
													<p><small>符合条件的产品档案总数：<span style="color: red;" id="num"></span>例</small></p>
												</div>
											</div>
											
											<div class="panel-body bbody">
												<table id="tab" >
													<thead>
														<tr style="background-color: #e8e8e8;">
															<td>产品编号</td>
															<td>产品名称</td>
															<td>用途类型</td>
															<td>单位</td>
															<td>成本单价</td>
															<td>入库</td>
														</tr>
													</thead>
													<tbody id="template2" style="display: none">
														<tr>
															<td class="productId"></td>
															<td class="productName"></td>
															<td class="type"></td>
															<td class="amountUnit"></td>
															<td class="realCostPrice"></td>
															<td class="warehouse"><a href="">入库</a></td>
														</tr>
													</tbody>
													<tbody id="productTbl">

													</tbody>
												</table>
											</div>
											
											<div class="panel-footer ffooter">
												<div id="footerDiv">
													<label style="font-weight: 700;">总数：<span style="color: red;" id="total">5</span>例&nbsp;&nbsp;&nbsp;&nbsp;
														当前第<span style="color: red;" id="pageNum">1</span>页&nbsp;&nbsp;&nbsp;&nbsp;
														共<span style="color: red;" id="pages">1</span>页&nbsp;&nbsp;&nbsp;&nbsp;
													</label>
												</div>
											</div>
										</div>
									</form>
								</div>
							</div>
						</div>
						<div class="modal-footer">
							<button id="btnConcel" class="btn btn-danger" data-bs-dismiss="modal">
								关闭<span class="glyphicon glyphicon-remove"></span>
							</button>
						</div>
					</div>
				</div>
		</div>
		
<script type="text/javascript" src="/js/jquery-3.7.0.min.js"></script>
<script type="text/javascript" src="/bootstrap/bootstrap-5.3.3-dist/js/bootstrap.bundle.min.js"></script>
    <script type="text/javascript" src="/js/common.js"></script>
	<script type="text/javascript">
	$(function () {
		// 初始化时间
		setInterval(updateDateTime, 1000);

		// 初始化数据
		initData();
		// 初始化事件
		initEvent();

		$("#proRegistraModal").on("shown.bs.modal",function(){
			//弹窗后触发
			initproductTbl(1);
		})

		//点击删除按钮删除点选的行
		$("#delete").click(function (){
			let checkboxes = $("#template1 input[type='checkbox']:checked");
			if (checkboxes.length == 0){
				alert("请选择要删除的行");
				return;
			}
			if (confirm("确定要删除吗？")){
				checkboxes.each(function (){
					//删除sessionStorage中对应的id
					let id = $(this).parent().parent().find("td:eq(0)").attr("id");
					let Items = sessionStorage.getItem("IdItems");
					if (Items == null){
						return;
					}
					Items = JSON.parse(Items);
					for (let i = 0; i < Items.length; i++) {
						if (Items[i] == id){
							Items.splice(i,1);
							break;
						}
					}
					sessionStorage.setItem("IdItems",JSON.stringify(Items));
					$(this).parent().parent().remove();
				})
			}
		})
		$("#template1").on("input",".num-input", function () {
			let num = $(this).val();
			let row = $(this).parent().parent();
			let costPrice = $(row).find("td:eq(6)").text();
			let costPriceNum = parseFloat(costPrice);
			let numVal = parseFloat(num);
			let total = costPriceNum * numVal;
			row.find("td:eq(7)").text(total);

			let totalNum=0;
			let totalPrice=0;
			let rows = $("#template1 tr");
			console.log(rows)
			for (let i = 0; i < rows.length; i++) {
				let row = rows[i];
				let num = $(row).find("td:eq(4) input").val();
				let unitPrice = $(row).find("td:eq(7)").text();
				if(unitPrice!=""){
					totalPrice+=parseInt(unitPrice);
				}
				if(num!=""){
					totalNum+=parseInt(num);
				}
			}
			$("#amountSum").text(totalNum);
			$("#costPriceSum").text(totalPrice);

		})

		$("#submit").click(function () {
			if($("#template1 tr").length==0){
				alert("请添加产品(至少一种)");
				return;
			}
			let storer = $("#storer").text();//入库人
			let reason = $("#reason option:selected").val();//入库理由
			let amountSum = $("#amountSum").text(); //总件数
			let costPriceSum = $("#costPriceSum").text(); //总金额
			let register = $("#register").text(); //登记人
			let registerTime = $("#registerTime").text(); //登记时间
			let remark = $("#remark").val(); //备注

			let data = [];
			data.push({
                storer: storer, //入库人
                reason: reason, //入库理由
                amountSum: amountSum, //入库总数
                costPriceSum: costPriceSum, //总金额
                register: register, //登记人
                registerTime: registerTime, //登记时间
                remark: remark //备注
            })
            let rows = $("#template1 tr");
			for (let i = 0; i < rows.length; i++) {
				let row = rows[i];
				let productId = $(row).find("td:eq(2)").text();
				let productName = $(row).find("td:eq(1)").text();
				let productDescribe=$(row).find("td:eq(3)").text();
				let num = $(row).find(".num-input").val();
				if(num==""){
					alert("请输入编号为"+id+"的数量,才能预览");
					return;
				}

				let amountUnit = $(row).find("td:eq(5)").text();
				let costPrice = $(row).find("td:eq(6)").text();
				//小计
				let total = $(row).find("td:eq(7)").text();
				let obj = {
					productId: productId,
					productName: productName,
					productDescribe:productDescribe,//产品描述
					num: num,
					amountUnit: amountUnit,
					costPrice: costPrice,
					total: total
				}
				data.push(obj);
			}
			console.log(data)
			sessionStorage.setItem("data", JSON.stringify(data));
			window.location.href="/s-gather/Warehousing_Application_Registration_preview";
		})
	})
	function initproductTbl(pageNum) {
		let json = formDateToJson("searchForm");
		console.log(json);
		$.ajax({
			url: "/d-file/initialArchiveTable",
			type: "POST",
			data: json,
			contentType: "application/json",
			dataType: "json",
			success: function (data) {
				console.log(data);
				$("#num").text(data.total);
				$("#total").text(data.total);
				$("#pageNum").text(data.pageNum);
				$("#pages").text(data.pages);
				$("#productTbl").empty();

				let template = $("#template2").children();

				$.each(data.list, function (i, products) {
					let tr = template.clone();
					$.each(products,function (name,value) {
						if(name=="id"){
							let a='<a href="javascript:assignment(\'' + products['id'] +  '\')">入库</a>';
							tr.find(".warehouse").html(a);
						}
						tr.find("."+name).text(value);
					})
					$("#productTbl").append(tr);
				})
				sessionStorage.clear();
			}
		})
	}

	function assignment(id) {
		let IdItems = [];
		if(sessionStorage.getItem("IdItems") != null){
			IdItems = JSON.parse(sessionStorage.getItem("IdItems"));
		}
		if(IdItems.indexOf(id) != -1){
			alert("该产品已添加");
			return;
		}
		IdItems.push(id);
		sessionStorage.getItem("IdItems") == null? sessionStorage.setItem("IdItems",JSON.stringify(IdItems)) : sessionStorage.setItem("IdItems",JSON.stringify(IdItems));
		$.ajax({
			url: "/d-module/getMaterialById?id=" + id,
			type: "get",
			datatype: "json",
			success: function (data) {
				console.log(data);
				let row = "<tr>" +
						"<td class='ckbox' id='"+data.id+"'><input type='checkbox' /></td>" +
						"<td>" + data.productName + "</td>" +
						"<td>" + data.productId + "</td>" +
						"<td>" + data.productDescribe + "</td>" +
						"<td class='num'>" +
						"<input class='num-input' value='1'></td>" +
						"<td>" + data.personalUnit + "</td>" +
						"<td>" + data.costPrice + "</td>" +
						"<td>" + data.costPrice + "</td>" +
						"</tr>";
				$("#template1").append(row);
			}
		})
	}
	function updateDateTime(){
		let date = new Date();
		let year = date.getFullYear();
		let month = (date.getMonth() + 1).toString().padStart(2, '0');
		let day = date.getDate().toString().padStart(2,'0');
		let hours = date.getHours().toString().padStart(2,'0');
		let minutes = date.getMinutes().toString().padStart(2,'0');
		let seconds = date.getSeconds().toString().padStart(2,'0');
		let dateTimeStr = year+"-"+month+"-"+day+" "+hours+":"+minutes+":"+seconds;
		$("#registerTime").text(dateTimeStr);
	}

	// 初始化数据
	function initData() {
		// 初始化一级分类
		initialFirstLevel();
	}
	// 初始化事件
	function initEvent() {
		// 一级分类选择事件
		$('#firstLevel').on('change', function () {
			let firstId = $(this).val();
			if (firstId == '') {
				$('#secondLevel option:gt(0)').remove();
				$('#thirdLevel option:gt(0)').remove();
				return;
			}
			// 存储一级分类名称
			$('#firstKindName').val($(this).find('option:selected').text());
			// 初始化二级分类
			initialSecondLevel(firstId);
		});
		// 二级分类选择事件
		$('#secondLevel').on('change', function () {
			let secondId = $(this).val();
			if (secondId == '') {
				$('#thirdLevel option:gt(0)').remove();
				return;
			}
			// 存储二级分类名称
			$('#secondKindName').val($(this).find('option:selected').text());
			// 存储二级分类名称
			initialThirdLevel(secondId);
		});
		// 三级分类选择事件
		$('#thirdLevel').on('change', function () {
			let thirdId = $(this).val();
			if (thirdId == '') {
				return;
			}
			// 存储三级分类名称
			$('#thirdKindName').val($(this).find('option:selected').text());
		});

		$('#state').on('click', function (){
			window.location.href= "/s-cell/Formulat_safety_stock";
		})


	}
	function initialFirstLevel() {
		$.ajax({
			url: "/d-level-first/initialLevel",
			type: "get",
			dataType: "json",
			success: function (data) {
				console.log(data);
				let firstLevel = $('#firstLevel');
				$('#firstLevel option:gt(0)').remove();
				$('#secondLevel option:gt(0)').remove();
				$('#thirdLevel option:gt(0)').remove();
				for (let i = 0; i < data.length; i++) {
					let option = $('<option>');
					option.val(data[i].firstId);
					option.text(data[i].firstName);
					firstLevel.append(option);
				}
			}
		})
	}
	function initialSecondLevel(firstId) {
		$.ajax({
			url: "/d-level-second/initialLevel?firstId="+firstId,
			type: "get",
			dataType: "json",
			success: function (data) {
				console.log(data);
				let secondLevel = $('#secondLevel');
				$('#secondLevel option:gt(0)').remove();
				$('#thirdLevel option:gt(0)').remove();
				for (let i = 0; i < data.length; i++) {
					let option = $('<option>');
					option.val(data[i].secondId);
					option.text(data[i].secondName);
					secondLevel.append(option);
				}
			}
		})
	}
	function initialThirdLevel(secondId) {
		$.ajax({
			url: "/d-level-third/initialLevel?secondId="+secondId,
			type: "get",
			dataType: "json",
			success: function (data) {
				console.log(data);
				let thirdLevel = $('#thirdLevel');
				$('#thirdLevel option:gt(0)').remove();
				for (let i = 0; i < data.length; i++) {
					let option = $('<option>');
					option.val(data[i].thirdId);
					option.text(data[i].thirdName);
					thirdLevel.append(option);
				}
			}
		})
	}
</script>
</body>
</html>
